<template>
	<div>
		<el-button-group>
			<el-button @click="downloadExcel" type="primary" class="mr-20px!">下载大文件 Excel</el-button>
			<el-button type="success" @click="count++">点击操作{{ count }}</el-button>
		</el-button-group>
	</div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { writeFile, utils } from 'xlsx'
const count = ref(0)
const loading = ref(false)
const myWorker = new Worker('downloadWorker.js')
// const myWorker = new Worker('/downloadWorker.js', { type: 'module' })
/**模拟生成大文件数据 */
const generateLargeFileData = () => {
	const data = []
	for (let i = 0; i < 10000; i++) {
		data.push({
			id: i + 1,
			name: `User ${i + 1}`,
			email: `user${i + 1}@example.com`,
			age: Math.floor(Math.random() * 100) + 1
		})
	}
	return data
}

myWorker.onmessage = (event) => {
	let wb = event.data
	// 这里也会占用主线程的ui渲染
	writeFile(wb, 'test.xlsx')
	ElMessage.success('下载任务已在后台运行，可以继续操作界面其他任务')
}

/**下载大文件 */
const downloadExcel = async () => {
	const data = generateLargeFileData()
	myWorker.postMessage(data)
}
</script>
